package com.example.shopingcenter.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.shopingcenter.DateBase.ShoppingDbHelper;
import com.example.shopingcenter.MyApplication;
import com.example.shopingcenter.R;
import com.example.shopingcenter.enity.GoodsInfo;

public class ShoppingDetalsActivity extends AppCompatActivity implements View.OnClickListener {
    TextView tv_title, tv_count, tv_price, tv_descp,tv_name;
    ImageView iv_pic;
    private ShoppingDbHelper mdbHelper;
    private int mgoods_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_detals);

        tv_title = findViewById(R.id.tv_title);
        tv_count = findViewById(R.id.tv_count);
        tv_price = findViewById(R.id.tv_price);
        tv_descp = findViewById(R.id.tv_descp);
        tv_name= findViewById(R.id.tv_name);

        iv_pic = findViewById(R.id.iv_pic);

        findViewById(R.id.iv_back).setOnClickListener(this);
        findViewById(R.id.btn_add).setOnClickListener(this);
        findViewById(R.id.iv_cart).setOnClickListener(this);

        tv_count.setText(String.valueOf(MyApplication.getmApp().goodsCount));


        mdbHelper = ShoppingDbHelper.getDbHelper(this);


    }

    @Override
    protected void onResume() {
        super.onResume();
        showDetals();
    }

    private void showDetals() {
        //获取上一个页面传来的商品编号
        mgoods_id = getIntent().getIntExtra("goods_id", 0);
        if (mgoods_id > 0) {
            //根据商品编号查询商品数据库中的商品记录
            GoodsInfo info = mdbHelper.queryGoodsInfoById(mgoods_id);
            tv_name.setText(info.name);
            tv_title.setText(info.name);
            tv_price.setText(String.valueOf(info.price));
            tv_descp.setText(info.description);
            iv_pic.setImageURI(Uri.parse(info.picPath));


        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_cart:
                Intent intent = new Intent(ShoppingDetalsActivity.this, ShoppingCartActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_add:
                addToCart(mgoods_id);
                break;

        }
    }

    private void addToCart(int goods_id) {
        int count=++MyApplication.getmApp().goodsCount;
        tv_count.setText(String.valueOf(count));
        mdbHelper.insertCartInfo(goods_id);
        Toast.makeText(this, "已成功添加购物车", Toast.LENGTH_SHORT).show();

    }
}